<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司简称" prop="shortName">
        <el-input
          v-model="queryParams.shortName"
          placeholder="请输入公司简称"
          clearable
          style="width: 100px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="股票代码" prop="stockCode">
        <el-input
          v-model="queryParams.stockCode"
          placeholder="请输入股票代码"
          clearable
          style="width: 100px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column label="编号" prop="companyId" width="50" />
      <el-table-column label="公司名称" prop="companyName" :show-overflow-tooltip="true" width="250" />
      <el-table-column label="上级公司" prop="parentName" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="公司简称" prop="shortName" :show-overflow-tooltip="true" width="80" />
      <el-table-column label="股票代码" prop="stockCode" :show-overflow-tooltip="true" width="80" />
      <el-table-column label="关联产品列表" align="center" width="180">
        
        <template slot-scope="scope">
          <template v-if="scope.row.productList && scope.row.productList.length">
            <el-collapse v-model="scope.row.activeNames" @change="handleChange">
              <el-collapse-item 
                v-for="(category, index) in scope.row.productList" 
                :key="category.categoryId"
                :title="category.categoryName" 
                :name="(index + 1).toString()">
                <div v-if="category.products && category.products.length">
                  <div v-for="product in category.products" :key="product.productId" class="product-item">
                    {{ product.productName }}
                  </div>
                </div>
                <div v-else class="no-products">暂无产品</div>
              </el-collapse-item>
            </el-collapse>
          </template>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="原材料" width="180" >
        <template slot-scope="scope">
          <template v-if="scope.row.materialsList && scope.row.materialsList.length">
            <div v-for="(product, index) in scope.row.materialsList" :key="index">
              {{ index+1 }} - {{ product.productName }}
            </div>
          </template>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="经营产品" width="180" >
        <template slot-scope="scope">
          <template v-if="scope.row.operatingProductList && scope.row.operatingProductList.length">
            <div v-for="(product, index) in scope.row.operatingProductList" :key="index">
              {{ index+1 }} - {{ product.productName }}
            </div>
          </template>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="公司简介" prop="briefIntro" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="成长空间" prop="growthSpaceIntro" width="150" />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.companyId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公司配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" />
        </el-form-item>

        <el-form-item label="上级公司">
          <el-select
            v-model="form.parentId"
            style="width: 300px"
            filterable
            remote
            reserve-keyword
            placeholder="请输入公司名称"
            :remote-method="getCompanyList"
            :loading="initCompaniesLoading">
            <el-option
              v-for="item in companyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
      </el-form-item>

        <el-form-item label="公司简称" prop="shortName">
          <el-input v-model="form.shortName" placeholder="请输入公司简称" />
        </el-form-item>
        <el-form-item label="股票代码" prop="stockCode">
          <el-input v-model="form.stockCode" placeholder="请输入股票代码" />
        </el-form-item>

        <el-form-item label="公司简介" prop="briefIntro">
          <el-input v-model="form.briefIntro" type="textarea" placeholder="请输入公司简介" />
        </el-form-item>

        <el-form-item label="成长空间" prop="growthSpaceIntro">
          <el-input v-model="form.growthSpaceIntro" type="textarea" placeholder="请输入成长空间" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="原材料">
          <el-select
            v-model="form.materialsIds"
            style="width: 300px"
            size="medium"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入原材料名称"
            :remote-method="getMaterialsList"
            :loading="initMaterialsLoading">
            <el-option
              v-for="item in materialsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="经营产品">
          <el-select
            v-model="form.operatingProductIds"
            style="width: 300px"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入经营产品名称"
            :remote-method="getOperatingProductList"
            :loading="initOperatingProductLoading">
            <el-option
              v-for="item in operatingProductOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      
        <el-form-item label="母公司关联产品">
          <div class="sku-wrapper">
            <div class="sku_sorts">
              <div class="sku_sort" v-for="(productItem, idx0) in productAttr" :key="idx0">
                <div class="label flex-center">
                  <div class="flex-one">
                    <!-- 新增产品分类选择器 -->
                    <el-select
                        v-model="productItem.categoryId"
                        style="width: 200px; margin-bottom: 10px;"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择产品分类"
                        :remote-method="getCategoryList"
                        :loading="initCategoriesLoading">
                        <el-option
                          v-for="item in categoryOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                    </el-select>
                    
                    <el-select
                        v-model="productItem.productIds"
                        style="width: 300px"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入产品名称"
                        :remote-method="getProductList"
                        :loading="initProductsLoading">
                        <el-option
                          v-for="item in productOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                    </el-select>
                  </div>
                  <a class="red" @click="deleteProductCategory(idx0)" style="margin-left: 10px;">删除关联产品</a>
                </div>
              </div>
            </div>
            <el-button @click="addProductCategory" type="primary" plain size="small" :disabled="isAddMode">+添加关联产品</el-button>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCompany, getCompany, delCompany, addCompany, updateCompany, changeCompanyStatus} from "@/api/pms/company";
// import { treeselect as industryTreeselect, companyIndustryTreeselect } from "@/api/pms/industry"
import { listProduct, companyProduct as getCompanyProductRelate} from "@/api/pms/product"
import { listCompanyProductCategory } from "@/api/pms/companyProductCategory"

export default {
  name: "Company",
  dicts: ['sys_normal_disable'],
  data() {
    return {

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公司表格数据
      companyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      productOptions: [],
      productIds: [],
      initProductsLoading: false,
      categoryOptions: [],
      initCategoriesLoading: false,
      currentCompanyId: null, // 添加当前公司ID
      parentId: null,
      companyOptions: [],
      initCompaniesLoading: false,
      initMaterialsLoading: false,
      materialsOptions: [],
      operatingProductOptions: [],
      initOperatingProductLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: undefined,
        shortName: undefined,
        stockCode: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ]
      },
      productAttr: [],
      activeNames: ['1']
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleChange(val) {
        console.log(val);
      },
    /** 查询公司列表 */
    getList() {
      this.loading = true;
      listCompany(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.companyList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    /**** 查询公司列表 */
    getCompanyList(query) {
      if (query !== '') {
        let params = { companyName: query }
        listCompany(params).then(response => {
          this.companyOptions = response.rows.map(item => {
              return {
                value: item.companyId,
                label: item.companyName
              };
            });
          this.initCompaniesLoading = false;
        })
      }
    },

    /**** 查询产品分类列表 */
    getCategoryList(companyId) {
      this.initCategoriesLoading = true;
      let params = {
        companyId: companyId
      };
      
      listCompanyProductCategory(params).then(response => {
        this.categoryOptions = response.rows.map(item => {
          return {
            value: item.categoryId,
            label: item.categoryName
          };
        });
        this.initCategoriesLoading = false;
      }).catch(() => {
        this.initCategoriesLoading = false;
      });
    },

    /**** 查询原材料列表 */
    getMaterialsList(query) {
      if (query !== '') {
        let params = { productName: query }
        listProduct(params).then(response => {
          this.materialsOptions = response.rows.map(item => {
              return {
                value: item.productId,
                label: item.productName
              };
            });
          this.initMaterialsLoading = false;
        })
      }
    },
    

    /**** 查询产品列表 */
    getMaterialsList(query) {
      if (query !== '') {
        let params = { productName: query }
        listProduct(params).then(response => {
          this.materialsOptions = response.rows.map(item => {
              return {
                value: item.productId,
                label: item.productName
              };
            });
          this.initMaterialsLoading = false;
        })
      }
    },

    /**** 查询产品列表 */
    getOperatingProductList(query) {
      if (query !== '') {
        let params = { productName: query }
        listProduct(params).then(response => {
          this.operatingProductOptions = response.rows.map(item => {
              return {
                value: item.productId,
                label: item.productName
              };
            });
          this.initOperatingProductsLoading = false;
        })
      }
    },

    /**** 查询产品列表 */
    getProductList(query) {
      if (query !== '') {
        let params = { productName: query }
        listProduct(params).then(response => {
          this.productOptions = response.rows.map(item => {
              return {
                value: item.productId,
                label: item.productName
              };
            });
          this.initProductsLoading = false;
        })
      }
    },

    /** 根据公司ID查询产品列表 */
    initOperatingProductOptions(response) {
      this.operatingProductOptions = response.data.operatingProductList.map(item => {
              return {
                value: item.productId,
                label: item.productName
              };
            });
      this.form.operatingProductIds = response.data.operatingProductIds;
    },

    initMaterialsOptions(response) {
      this.materialsOptions = response.data.materialsList.map(item => {
              return {
                value: item.productId,
                label: item.productName
              };
            });
      this.form.materialsIds = response.data.materialsIds;
    },

    /** 更加父id查询父公司名称 */
    getParentName(parentId) {
      return getCompany(parentId).then(response => {
        if (response && response.data) {
          this.companyOptions = [{
            value: response.data.companyId,
            label: response.data.companyName
          }];
          this.form.parentId = response.data.companyId;
        }
      })
    },

    /** 加载公司关联产品数据 */
    loadCompanyProducts(companyId) {
      getCompanyProductRelate(companyId).then(response => {
        if (response.data && response.data.length > 0) {
          // 将后端返回的关联产品数据转换为前端需要的格式
          this.productAttr = response.data.map(item => ({
            categoryId: item.categoryId,
            productIds: item.productIds || []
          }));
          
          // 同时更新产品选项数据，用于产品选择器显示
          this.updateProductOptions(response.data);
        } else {
          // 如果没有关联产品数据，初始化一个空的关联项
          this.productAttr = [{
            categoryId: undefined,
            productIds: []
          }];
        }
      }).catch(() => {
        // 请求失败时，初始化一个空的关联项
        this.productAttr = [{
          categoryId: undefined,
          productIds: []
        }];
      });
    },

    /** 更新产品选项数据 */
    updateProductOptions(categoryData) {
      // 将所有分类下的产品合并到productOptions中
      const allProducts = [];
      categoryData.forEach(category => {
        if (category.products && category.products.length > 0) {
          category.products.forEach(product => {
            allProducts.push({
              value: product.productId,
              label: product.productName
            });
          });
        }
      });
      
      // 去重并更新productOptions
      const uniqueProducts = allProducts.filter((product, index, self) => 
        index === self.findIndex(p => p.value === product.value)
      );
      
      this.productOptions = uniqueProducts;
    },

    // 公司状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.companyName + '"公司吗？').then(function() {
        return changeCompanyStatus(row.companyId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.productOptions = [];
      this.companyOptions = [];
      this.productAttr = [];
      this.currentCompanyId = null;
      this.form = {
        companyId: undefined,
        parentId: undefined,
        companyName: undefined,
        shortName: undefined,
        stockCode: undefined,
        status: "0",
        briefIntro: undefined,
        growthSpaceIntro: undefined,
        productIds: []
      };
      this.resetForm("form");
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.companyId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.open = true;
      this.title = "添加公司";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const companyId = row.companyId || this.ids;
      this.currentCompanyId = companyId;
      this.getCategoryList(companyId);
      this.loadCompanyProducts(companyId);
      getCompany(companyId).then(response => {
        this.form = response.data;
        if (response.data.parentId > 0) {
          this.getParentName(this.form.parentId);
        }else{
          this.form.parentId = undefined
        }
        this.initMaterialsOptions(response);
        this.initOperatingProductOptions(response);
        this.open = true;
        this.title = "修改公司";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 构建提交数据，包含产品分类和产品列表的组合
          const submitData = {
            ...this.form,
            productCategories: this.productAttr.map(item => ({
              categoryId: item.categoryId,
              productIds: item.productIds
            })).filter(item => item.categoryId && item.productIds.length > 0) // 过滤掉无效数据
          };
          if (this.form.companyId != undefined) {
            
            updateCompany(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            
            addCompany(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const companyIds = row.companyId || this.ids;
      this.$modal.confirm('是否确认删除公司编号为"' + companyIds + '"的数据项？').then(function() {
        return delCompany(companyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pms/company/export', {
        ...this.queryParams
      }, `company_${new Date().getTime()}.xlsx`)
    },

    addProductCategory() {
      this.productAttr.push({
        categoryId: undefined, // 产品分类ID
        productIds: [] // 产品ID数组
      })
    },
    deleteProductCategory(idx) {
      this.productAttr.splice(idx, 1);
    },
  },
  computed: {
    isAddMode() {
      return !this.currentCompanyId; // 没有companyId表示是新增模式
    }
  }
};
</script>